﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OnlineVideos.UI;
using OnlineVideos.Common;
using OnlineVideos.Data;
using Common.Library;
using OnlineVideos.View_Models;


using Common.Utilities;
using System.Windows.Navigation;

using System.ComponentModel;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using Microsoft.Phone.Shell;
using PicasaMobileInterface;
using System.Windows.Threading;
using Microsoft.Phone.BackgroundAudio;

namespace OnlineMovies.Views
{
    public partial class VideoGamesDetail : PhoneApplicationPage
    {
        string navigationvalue = string.Empty;
        string pivotindex = string.Empty;
        PivotItem currentItem = default(PivotItem);
        bool appbarvisible = true;
        string background = "0";
        string chapter = string.Empty;
        public DispatcherTimer storyboardtimer;
        public VideoGamesDetail()
        {
            InitializeComponent();
            if (AppSettings.ShowID != "0")
            {
                LoadPivotThemes(AppSettings.ShowUniqueID);
                //TODO: Save title also in settings or pass through query string
                tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
                background = "1";
                if (!ShowCastManager.ShowGamePivot(AppSettings.ShowID))
                {
                    pvtMainDetails.Items.Remove(gamepivot);
                }
            }
           Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded);

        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstaSongs, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
           
            try
            {
                if (ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
                    LoadAds();
                FlurryWP8SDK.Api.LogEvent("VideoGamesDetail Page", true);
                performanceProgressBar.IsIndeterminate = true;

               
                int showid = Convert.ToInt32(AppSettings.ShowID);
                string sharedstatus = Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.ShareStatus;
                if (sharedstatus == "Shared To Blog")
                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Shared To Blog)";
                else
                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Not Shared)";
                if (background == "0")
                {
                    LoadPivotThemes(AppSettings.ShowUniqueID);
                    tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
                }
                performanceProgressBar.IsIndeterminate = false;
                PageHelper.RemoveEntryFromBackStack("VideoGameDetail");
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in PhoneApplicationPage_Loaded Method In VideoGamesDetail.cs file.", ex);
            }
        }
        #region Private Methods
       private void LoadPivotThemes(long ShowID)
        {
            pvtMainDetails.Background = ShowDetail.LoadShowPivotBackground(ShowID);
           
        }
        #endregion
        private void imgTitle_MouseEnter(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }
        private void pvtMainDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                currentItem = e.AddedItems[0] as PivotItem;
                if (appbarvisible == true)
                {
                    if (currentItem != null)
                    {
                        if (currentItem.Header.ToString() == "detail")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Edit" + " " + "description";
                            else
                            {
                                ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Edit" + " " + "description");
                                appBarMenuitem.Click += btnadd_Click_1;
                                this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                            }
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                       else if (currentItem.Header.ToString() == "game")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                        else if (currentItem.Header.ToString() == "cheats")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                        else if (currentItem.Header.ToString() == "weapons")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                        else if (currentItem.Header.ToString() == "vehicles")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                        else if (currentItem.Header.ToString() == "missions")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                        else if (currentItem.Header.ToString() == "achievements")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                        else if (currentItem.Header.ToString() == "controls")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 2)
                                this.ApplicationBar.MenuItems.RemoveAt(1);
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                        }
                        else
                        {
                            if (this.ApplicationBar.MenuItems.Count < 2)
                            {
                                ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Add" + " " + currentItem.Header.ToString());
                                appBarMenuitem.Click += btnadd_Click_1;
                                this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                            }
                            else
                            {
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add" + " " + currentItem.Header.ToString();
                            }
                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;

                        }
                    }
                }
                if (pvtMainDetails.SelectedIndex == 2)
                {
                    BackgroundHelper bwhelper = new BackgroundHelper();
                    bwhelper.AddBackgroundTask(
                    (object s, DoWorkEventArgs a) =>
                    {
                        addgame();
                    },
                    (object s, RunWorkerCompletedEventArgs a) =>
                    {

                    }
                    );

                    bwhelper.RunBackgroundWorkers();
                    bwhelper.StartScheduledTasks();
                }
                else
                {
                    if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                    {
                        if (BackgroundAudioPlayer.Instance != null && BackgroundAudioPlayer.Instance.Track.Source.ToString().Contains("Claps.mp3"))
                        {
                            BackgroundAudioPlayer.Instance.Stop();
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in pvtMainDetails_SelectionChanged Method In ShowDetails.cs file", ex);
            }


        }
        public void addgame()
        {
            try
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    if (!ShowCastManager.ShowGameControl(AppSettings.ShowID))
                    {
                        storyboardtimer = new DispatcherTimer();
                        storyboardtimer.Interval = TimeSpan.FromSeconds(2);
                        storyboardtimer.Tick += new EventHandler(storyboardtimer_Tick);
                        storyboardtimer.Start();
                    }

                });
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in addgame Method In ShowDetails.cs file", ex);
            }

        }


        void storyboardtimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (pvtMainDetails.SelectedIndex == 2)
                {
                    if (OnlineVideos.Game.GameInstance.gameopened == false)
                    {
                        foreach (OnlineVideos.Game.MemoryCard m in OnlineVideos.Game.GameInstance.stopstoryboard)
                        {
                            m.storyboardfromx = "3";
                            m.storyboardtox = "-3";
                            m.storyboardfromy = "3";
                            m.storyboardtoy = "-3";
                            m.storyboardfromz = "3";
                            m.storyboardtoz = "-3";
                        }
                        storyboardtimer.Stop();
                    }
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in storyboardtimer_Tick Method In ShowDetails.cs file", ex);
            }
        }
        private void btnadd_Click_1(object sender, EventArgs e)
        {
            try
            {
                if ((sender as ApplicationBarMenuItem).Text.Contains("characters"))
                {
                    Constants.DownloadTimer.Stop();
                    NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.RelativeOrAbsolute));
                }
                else if ((sender as ApplicationBarMenuItem).Text.Contains("description"))
                {
                    Constants.DownloadTimer.Stop();
                    Constants.editdescription = true;
                    NavigationService.Navigate(new Uri("/Views/Description.xaml", UriKind.RelativeOrAbsolute));
                }
                else if ((sender as ApplicationBarMenuItem).Text.Contains("asanas"))
                {
                    Constants.DownloadTimer.Stop();
                    NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.RelativeOrAbsolute));
                }
                else
                {


                    if ((sender as ApplicationBarMenuItem).Text.Contains("videos"))
                    {
                        Constants.DownloadTimer.Stop();
                        Constants.Linkstype = "Songs";
                        NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + string.Empty, UriKind.Relative));
                    }



                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in btnadd_Click_1 Method In ShowDetails.cs file", ex);
            }
        }

        private void btnshare_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (NetworkHelper.IsNetworkAvailableForDownloads())
                {
                    UploadToBlog upload = new UploadToBlog(AppSettings.ShowUniqueID, page1: this);
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in btnshare_Click_1 Method In ShowDetails.cs file", ex);
            }
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("VideoGamesDetail Page");

            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In VideoGamesDetail.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                string id = "";
                if (NavigationContext.QueryString.TryGetValue("id", out id))
                {
                    AppSettings.ShowID = id;

                }
                int showid = Convert.ToInt32(AppSettings.ShowID);
                FlurryWP8SDK.Api.LogPageView();
                if (Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync().Result.Status != "Custom")
                {
                    this.ApplicationBar.IsVisible = false;
                    appbarvisible = false;
                }
                else
                {
                    this.ApplicationBar.IsVisible = true;
                }
                if (NavigationContext.QueryString.TryGetValue("navigationvalue", out navigationvalue))
                {

                    if (navigationvalue == "1")
                    {
                        if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                            pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                        Constants.navigationvalue++;
                    }
                    else
                    {
                        if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                            pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                        Constants.navigationvalue--;
                    }
                    while (NavigationService.BackStack.Count() > 1)
                    {
                        if (!NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("ShowDetails"))
                        {
                            NavigationService.RemoveBackEntry();
                        }
                        else
                        {
                            NavigationService.RemoveBackEntry();
                            break;
                        }
                    }
                }
                if (VideosList.lbxSongsList.IsEnabled == false)
                    VideosList.lbxSongsList.IsEnabled = true;
                //YouTube.CancelPlay();
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In VideoGamesDetail.cs file.", ex);
            }
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            //if (YouTube.CancelPlay())
            //    e.Cancel = true;

            base.OnBackKeyPress(e);
        }
    }
}